package mujmail;

/*
MujMail - Simple mail client for J2ME
Copyright (C) 2006 Nguyen Son Tung <n.sontung@gmail.com>
Copyright (C) 2008 David Hauzar <david.hauzar.mujmail@gmail.com>
 
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

import mujmail.util.Functions;
import java.util.Enumeration;
import javax.microedition.lcdui.AlertType;
import lcduilwuit.Form;
import lcduilwuit.ItemStateListener;
import lcduilwuit.ChoiceGroup;
import lcduilwuit.Choice;
import lcduilwuit.Item;
import lcduilwuit.TextField;
import lcduilwuit.StringItem;
import lcduilwuit.Command;
import lcduilwuit.List;
import lcduilwuit.Displayable;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.media.control.*;
import javax.microedition.media.*;

import mujmail.account.MailAccount;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.MediaComponent;

import javax.microedition.io.file.*;
import javax.microedition.io.*;
import java.io.*;

/**
 * The form for creating new mail.
 * 
 * TODO: better handling of messages which are edited in createAndSaveMessageHeader
 * 
 * TODO: Better comments
 * 
 * Implementation detail: Attachments must be last items in this form.
 * Otherwise removing attachments will not work and there will be removed
 * another items. See method FSAttachemtsAdder.removeAllAttachements()
 * 
 * @see FSAttachmentsAdder#removeAllAttachments()
 */
public class SendMail extends Form  implements ItemStateListener, ActionListener{
    
    private static final boolean DEBUG = false;

    /** The name of this source file */
    private static final String SOURCE_FILE = "SendMail";

    private Displayable nextScreen;

    static final byte NORMAL = 0;
    /** Editing message. That means that the content of old one will
     * be displayed to user, he edits it and than the content of old 
     * one will be rewritten by new content. */
    static final byte EDIT = 1;
    static final byte REPLY = 2;
    static final byte FORWARD = 3;
    /**
     * Bouncing message. That means that the content of old one will
     * be displayed to user, he edits it and than he can send it. The 
     * content of old one will be not rewritten.
     */
 
    /** The header of the message which will be created from this form */
    byte mode = NORMAL;
    TextField to, bcc, cc, subject;// /*body,*/
    Object selectedField;

    TextArea body;
    private StringItem from;
    Command ok, cancel, send, sendLater, draft, bc, clear, addRcp, chooseAccount;//, editBody, updateBody, cancelBody;
    boolean bcc_cc_added;
      // TODO (Betlista): comment this, why is this persistent box called "callBox" ?
    PersistentBox callBox;
    MujMail mujMail;
  //#ifdef SONIMMAIL_CAMERA
    Command addSnapshot;
//#endif
    //#ifdef SONIMMAIL_VOICEMAIL
    Command addVoice;
//#endif
    //#ifdef MUJMAIL_FS
    // Filesystem 
    /** Handles the support of filesystem in SendMail form */
    private FSAttachmentsAdder attachementsAdder = null;

    public FSAttachmentsAdder getAttachementsAdder() {
        return attachementsAdder;
    }
    //#endif
    public void actionPerformed(ActionEvent evt) {
        com.sun.lwuit.Command c = evt.getCommand();
        //#ifdef MUJMAIL_FS
        if (c == getAttachementsAdder().attach) {
            getAttachementsAdder().attachFileSelection();
        }
        //#endif
        if (c == bc) {
            addBc();
            //#ifdef SONIMMAIL_CAMERA
        } else if (c == addSnapshot) {
            new SnapshotForm(this, this).show();
            //#endif
            //#ifdef SONIMMAIL_VOICEMAIL
        } else if (c == addVoice) {
            new SoundRecordForm(this, this).show();

            //#endif
        } else if (c == send) {
            if (!hasValidRecipients()) {
                Dialog.show(Lang.get(Lang.EXTRA_ERROR), "100: " + Lang.get(Lang.ALRT_SM_NO_RCP), Dialog.TYPE_ERROR, null, Lang.get(Lang.BTN_OK), "");//,5);
                return;
            }
            selectedField = null;
            OutBox box = (c == draft) ? mujMail.draft : mujMail.outBox;
            if (box.isBusy()) {
                mujMail.alert.setAlert(null, this, Lang.get(Lang.ALRT_SYS_BUSY), MyAlert.DEFAULT, AlertType.INFO);
            } else {
                // myDisplay.setCurrent(box);
                mujMail.mainMenu();
                box.sendSingle(box.addOutMail(this));
            }
        } else if (c == sendLater || c == draft) {
            if (c == sendLater && !hasValidRecipients()) {
                Dialog.show(Lang.get(Lang.EXTRA_ERROR), "100: " + Lang.get(Lang.ALRT_SM_NO_RCP), Dialog.TYPE_ERROR, null, Lang.get(Lang.BTN_OK), "");//,5);
                return;
            }

            selectedField = null;
            OutBox box = (c == draft) ? mujMail.draft : mujMail.outBox;
            if (box.isBusy()) {
                mujMail.alert.setAlert(null, this, Lang.get(Lang.ALRT_SYS_BUSY), MyAlert.DEFAULT, AlertType.INFO);
            } else {
                //  if (sendMail.mode != SendMail.NORMAL) {
                //     myDisplay.setCurrent(sendMail.callBox);
                //}
                box.addOutMail(this);
                mujMail.mainMenu();
            }
        } else if (c == clear) {
            clear();
        } else if (c == cancel) {
            selectedField = null;
            if (mode != SendMail.NORMAL) {
                clear();
                mode = SendMail.NORMAL;
            }

            showNextScreen();
        } else if (c == addRcp) {
            //mujMail.getAddressBook().addEmails(this);
            new AddressBook(mujMail).addEmails(this);
        } else if (c == chooseAccount) {
            chooseAccounts();
        }


    }



    /**
     * Shows form with active account list. 
     * Permit users to select mail used as sender (From entry)
     */
    class AccountsForm extends com.sun.lwuit.Dialog implements ActionListener{
        ChoiceGroup accountsCG;
        public AccountsForm() {
            super(Lang.get(Lang.AS_ACCOUNTS));
            accountsCG = new ChoiceGroup(Lang.get(Lang.SM_SENDING_ACCOUNT), Choice.EXCLUSIVE);
            addComponent(accountsCG);
            addCommand(ok);
            addCommand(cancel);
            setCommandListener(this);
        }

        public void actionPerformed(ActionEvent evt) {
            if (evt.getCommand() == ok) {
            from.setText(accountsCG.getString(accountsCG.getSelectedIndex()));
            dispose();
            } else if (evt.getCommand() == cancel) {
                dispose();//myDisplay.setCurrent(sendMail);
            }
        }

        public void refresh() {
            if (!mujMail.getInBox().hasAccountToRetrieve()) {
                mujMail.alert.setAlert(this, (Displayable)null, Lang.get(Lang.ALRT_AS_NO_ACCOUNT_SET_ACTIVE), MyAlert.DEFAULT, AlertType.WARNING);
                return;
            }

            //markAsDeleted old things
            for (int i = accountsCG.size() - 1; i >= 0; --i) {
                accountsCG.delete(i);
            }

            int i = 0;
            //let's show the primary account on the first place
            if (!Settings.primaryEmail.equals(Settings.notSetPE)) {
                accountsCG.append(Settings.primaryEmail, null);
                accountsCG.setSelectedIndex(i, true);
                ++i;
            }


            //let's list all of the active rest			
            for (Enumeration e = mujMail.getMailAccounts().elements(); e.hasMoreElements();) {
                MailAccount account = (MailAccount) e.nextElement();
                if (account.isActive() && !account.getEmail().equals(Settings.primaryEmail)) {
                    accountsCG.append(account.getEmail(), null);
                    //if it was selected already, select it
                    if (account.getEmail().equals(from.getText())) {
                        accountsCG.setSelectedIndex(i, true);
                    }
                    ++i;
                }
            }

            //lets choose the primary or the first one if none was selected
            if (accountsCG.getSelectedIndex() == -1) {
                accountsCG.setSelectedIndex(0, true);
            }

            show();
            // mujMail.getDisplay().setCurrent(this);
        }
    }

    public SendMail(MujMail mujMail) {
        super(Lang.get(Lang.AC_WRITE_MAIL));
        
//        header = new MessageHeader(mujMail.outBox);
        
        this.mujMail = mujMail;

        from = new StringItem(Lang.get(Lang.ML_FROM), "");
        if ( Properties.textFieldMailIncorrect ) {
            bcc = new TextField("Bcc:", "", 256, TextField.ANY);
            cc = new TextField("Cc:", "", 256, TextField.ANY);
            to = new TextField(Lang.get(Lang.ML_TO), "", 256, TextField.ANY); 
        } else {
            bcc = new TextField("Bcc:", "", 256, TextField.EMAILADDR);
            cc = new TextField("Cc:", "", 256, TextField.EMAILADDR);
            to = new TextField(Lang.get(Lang.ML_TO), "", 256, TextField.EMAILADDR); 
        }
        subject = new TextField(Lang.get(Lang.ML_SUBJECT), "", 256, TextField.ANY);
        body = new TextArea(5,5){
        public void keyRepeated(int keyCode)
        {

        }
        public void keyReleased(int keyCode)
        {
            int gameKey = com.sun.lwuit.Display.getInstance().getGameAction(keyCode);
            if (gameKey != com.sun.lwuit.Display.GAME_DOWN &&
                    gameKey != com.sun.lwuit.Display.GAME_UP &&
                    gameKey != com.sun.lwuit.Display.GAME_LEFT &&
                    gameKey != com.sun.lwuit.Display.GAME_RIGHT &&
                    gameKey != com.sun.lwuit.Display.GAME_FIRE)
            {
                fireClicked();
                return;
            }
            super.keyReleased(keyCode);
        }
        };//TextField(Lang.get(Lang.ML_BODY), "", 5000, TextField.ANY);
        //#ifdef SONIMMAIL_CAMERA
        addSnapshot = new Command("Attach snapshot");
        //#endif
        //#ifdef SONIMMAIL_VOICEMAIL
        addVoice=new Command("Attach voice clip");
        //#endif
        cancel = new Command(Lang.get(Lang.BTN_CANCEL), Command.BACK, 5);
        addCommand(cancel);
        //#ifdef MUJMAIL_FS
        if ( Properties.JSR75Available() == true) {
            attachementsAdder = new FSAttachmentsAdder(this);
        }
        //#endif
        ok = new Command(Lang.get(Lang.BTN_OK), Command.OK, 0);
        send = new Command(Lang.get(Lang.BTN_SM_SEND), Command.ITEM, 1);
        addRcp = new Command(Lang.get(Lang.BTN_SM_USE_AB), Command.ITEM, 2);
        sendLater = new Command(Lang.get(Lang.BTN_SM_SEND_LATTER), Command.ITEM, 3);
        draft = new Command(Lang.get(Lang.BTN_SAVE), Command.ITEM, 4);
        bc = new Command(Lang.get(Lang.BTN_SM_BC), Command.ITEM, 5);
        clear = new Command(Lang.get(Lang.BTN_SM_CLEAR), Command.ITEM, 7);
        chooseAccount = new Command(Lang.get(Lang.BTN_SM_CHOOSE_FROM), Command.ITEM, 8);
        append(to);
        append(subject);
        addComponent(body);// append(body);
        addCommand(bc);
        addCommand(addRcp);
        addCommand(send);
        addCommand(sendLater);
        addCommand(draft);
        addCommand(clear);
        addCommand(chooseAccount);
        //#ifdef SONIMMAIL_CAMERA
        addCommand(addSnapshot);
        //#endif
        //#ifdef SONIMMAIL_VOICEMAIL
        addCommand(addVoice);
        //#endif
        setCommandListener(this);
        setItemStateListener(this);

    }
    
    /* *
     * Creates the message from this form.
     * @return
     */
//    public MessageHeader createMessage() {
//    }

    public void itemStateChanged(Item item) {
        selectedField =  item;
    }
    
   public Object getSelectedItem() {
        return selectedField;
    }

    public void replyAll(MessageHeader header) {
        nextScreen = MujMail.mujmail.getMenu();//MujMail.mujmail.mailForm;

        quotedReply(header);
        String rcps = header.getRecipients();
        int x = rcps.indexOf("Bcc:");
        int y = rcps.indexOf("Cc:");
        int z = rcps.indexOf("To:");
        String fromEmail=header.getFrom();
        if(header.getReplyTo()!=null && !header.getReplyTo().equals(""))
           fromEmail=header.getReplyTo();
       String[] recps={"","",""};
        if (x != -1) {
           recps[0]=rcps.substring(x + 4, rcps.indexOf(" *", x + 5)).trim();
        }
        if (y != -1) {
            recps[1]=rcps.substring(y + 3, rcps.indexOf(" *", y + 4)).trim();
        }
        if (z != -1) {
            recps[2]=rcps.substring(z + 3, rcps.indexOf(" *", z + 4)).trim();
        }
        recps[2]=recps[2]+fromEmail;
        for (int i = 0; i < recps.length; i++) {
            System.out.println("i="+i+"     recps"+recps[i]);
            if (recps[i].indexOf(header.getAccountID()) != -1) {
                int start = recps[i].lastIndexOf(',', recps[i].indexOf(header.getAccountID()));
                int end = recps[i].indexOf(",", recps[i].indexOf(header.getAccountID()));
                if (start == -1 && end == -1) {
                    recps[i] = "";
                } else if (start == -1 && end != -1) {
                    recps[i] = recps[i].substring(end + 1);
                } else if (start != -1 && end == -1) {
                    recps[i].substring(0, start);
                }

            }
        }
        bcc.setString(recps[0]);
        cc.setString(recps[1]);
        to.setString(recps[2]);
        if(recps[0].length()>0 || recps[1].length()>0)
             addBc();
    }

    public void reply(MessageHeader header) {
        nextScreen = MujMail.mujmail.getMenu();//MujMail.mujmail.mailForm;

        mode = REPLY;
        from.setText(header.getAccountID());
        if(header.getReplyTo()!=null &&!header.getReplyTo().equals("") )
        {
             to.setString(header.getReplyTo().trim());
        }
        else
        {
            to.setString(header.getFrom().trim());
        }
       
        if (header.getSubject().toLowerCase().startsWith("re:")) {
            subject.setString(header.getSubject());
        } else {
            subject.setString("Re: " + header.getSubject());
        }
        this.callBox = header.getBox();
        mujMail.getDisplay().setCurrent(this);
    }

    public void quotedReply(MessageHeader header) {
        nextScreen = MujMail.mujmail.getMenu();//MujMail.mujmail.mailForm;
        if (header.getBodyPartCount() == 0 || !(header.getBpType((byte) 0) == BodyPart.TYPE_HTML || header.getBpType((byte) 0) == BodyPart.TYPE_TEXT)) {
            mujMail.alert.setAlert(null, (Displayable)null, Lang.get(Lang.ALRT_SM_CAN_NOT_ATTACH_BODY), MyAlert.DEFAULT, AlertType.WARNING);
        } else {
            if ((header.getBpType((byte) 0) == BodyPart.TYPE_TEXT || header.getBpType((byte) 0) == BodyPart.TYPE_HTML) && header.getBpState((byte) 0) <= BodyPart.BS_PARTIAL) {
                StringBuffer newBody=null;
                String str = header.getBodyPartContent((byte) 0);
                byte[] strByte =str.getBytes() ;
                if(strByte.length>MailForm.MAX_SIZE_TEXT)
                  newBody =new StringBuffer(new String(strByte,0,MailForm.MAX_SIZE_TEXT)+" ["+Lang.get(Lang.EXTRA_MSG_TRUCATED)+"]");
                 else
                    newBody = new StringBuffer(str);

                int i = 0;
                newBody.insert(i, '>');
                while (i < newBody.length()) {
                    if (newBody.charAt(i) == '\n') {
                        newBody.insert(i + 1, '>');
                        i += 2;
                    } else {
                        i++;
                    }
                }
                if (newBody.length() > body.getMaxSize()) {
                    body.setMaxSize(newBody.length() + 1000);
                }
          //      body.setString("\r\n" + newBody.toString() + "\r\n");
                body.setText("\r\n" + newBody.toString() + "\r\n");
            }
            reply(header);
        }
    }

    public void edit(MessageHeader header, Displayable nextScreen) {
      //  byte mode = (callBox instanceof InBox) ? BOUNCE : EDIT;
        edit(header, nextScreen, EDIT);//mode);
    }

    private void edit(MessageHeader header, Displayable nextScreen, byte mode) {
//        this.header = header;
        this.nextScreen = nextScreen;
        this.mode = mode;
        String accountID=header.getAccountID();
        String fromEmail=header.getFrom();

        if(mode==FORWARD)
        {
            try{
                fromEmail=((MailAccount)MujMail.mujmail.getMailAccounts().get(accountID)).getEmail();
            }catch(Exception e){
            System.out.println("Couldn't get from email");
            }
        }
        from.setText(fromEmail);//header.getFrom());
        String rcps = header.getRecipients();
        int x, y, z;
        //detect To: Bcc: Cc: 
        x = rcps.indexOf("Bcc:");
        y = rcps.indexOf("Cc:");
        z = rcps.indexOf("To:");
        if (z != -1) {
            to.setString(rcps.substring(z + 3, rcps.indexOf(" *", z + 4)).trim());
        }
        if(mode==FORWARD)
            to.setString("");

        if ((x != -1 || y != -1)) {
            //set(1, bcc);
            //set(2, cc);
      //      set(2, bcc); //Anup
       //     set(3, cc); //Anup
            removeComponent(cc);
             removeComponent(bcc);
             addComponent(getComponentIndex(to)+2,cc);
            addComponent(getComponentIndex(to)+3,bcc);


            if (x != -1) {
                bcc.setString(rcps.substring(x + 4, rcps.indexOf(" *", x + 5)).trim());
            }
            if (y != -1) {
                cc.setString(rcps.substring(y + 3, rcps.indexOf(" *", y + 4)).trim());
            }
       //     append(subject);
       //     append(body);
        //    addComponent(body);
            removeCommand(bc);
        }
           if(mode==FORWARD)
                subject.setString("Fw:"+header.getSubject());
           else
               subject.setString(header.getSubject());
        BodyPart bp = header.getBodyPart((byte) 0);
        try {
            if (mode == NORMAL || mode == EDIT) {
                body.setText(bp.getStorage().getContent());//setString(bp.getStorage().getContent());
            } else {
               ///* body.setString*/body.setText(
                 String hdr=  "\n---------- "+Lang.get(Lang.SM_FORWARDED_MESSAGE) +"----------\n" +
                    Lang.get(Lang.ML_FROM)+ header.getFrom() + "\n" +
                    Lang.get(Lang.EXTRA_DATE) + header.getTimeStr() + "\n" +
                    Lang.get(Lang.ML_SUBJECT) + header.getSubject() + "\n" + "" +
                    Lang.get(Lang.ML_RECIPIENTS) + header.getRecipients() + "\n" + "\n";
                    String bpStr=  header.getBodyPartContent((byte) 0);

                byte[] strByte = bpStr.getBytes();
                if(strByte.length>MailForm.MAX_SIZE_TEXT)
                {
                    bpStr = new String(strByte,0,MailForm.MAX_SIZE_TEXT)+" ["+Lang.get(Lang.EXTRA_MSG_TRUCATED)+"]";
                }
                body.setText(hdr+bpStr);
            }
        } catch (Throwable ex) {
            ex.printStackTrace();
        }

        //#ifdef MUJMAIL_FS
     //  if(mode!=FORWARD)
        attachementsAdder.importAttachmentsFromHeader(header);
        //#endif
        
        this.callBox = header.getBox();
        mujMail.getDisplay().setCurrent(this);
    }

    /**
     * Forward the message.
     * @param callBox
     */
    public void initForward(TheBox callBox, Displayable nextScreen) {
        edit(callBox.getSelectedHeader(), nextScreen, FORWARD);
    }

    public void addBc() {
        if (bcc_cc_added == false) {
          /*  set(2, bcc); //set subject textfield to bcc
            set(3, cc); //set body to cc
            append(subject);
        //    append(body);
            addComponent(body);
            if (mode == FORWARD) {
                if (DEBUG) System.out.println("DEBUG - SendMail.addBc - deleting old one");
                StringItem fwdMsgNotice = (StringItem) get(4);
                delete(4); //remove the old one
                append(fwdMsgNotice); //append again the forwarded message string item			
            }*/
            removeComponent(cc);
            removeComponent(bcc);
            addComponent(getComponentIndex(to)+2,cc);
            addComponent(getComponentIndex(to)+3,bcc);


            removeCommand(bc);
            bcc_cc_added = true;
        }
    }

    public void chooseAccounts() {
        new AccountsForm().refresh();
    }
    
    public boolean hasValidRecipients()
    {
        if(bcc.getString().length() == 0 &&
                cc.getString().length()==0 &&
                to.getString().length()==0)
            return false;
        if (bcc.getString().length() > 0 && bcc.getString().length() < 6) {
            return false;
        }
        if (to.getString().length() > 0 && to.getString().length() < 6) {
            return false;
        }
        if (cc.getString().length() > 0 && cc.getString().length() < 6) {
            return false;
        }
        return true;
    }
    /**
     * Creates the message from data filled in this form and saves it to the
     * database. If the storingBox is the same as {@link SendMail#callBox}
     * and mode is {@link SendMail#EDIT}, saves the message to already existing
     * record in the RMS database.
     * 
     * @param storingBox the box to which the header will be stored (will belong)
     * @return the message header of message created form data filled in this 
     *  form.
     */
    public MessageHeader createAndSaveMessage(PersistentBox storingBox) {
        StringBuffer rcps = new StringBuffer();
        String recipients;
        //now try to append all the recipients ()
        if (bcc.getString().length() != 0) {
            rcps.append("Bcc: ").append(bcc.getString()).append(" *");
        }
        if (cc.getString().length() != 0) {
            rcps.append("Cc: ").append(cc.getString()).append(" *");
        }
        if (to.getString().length() != 0) {
            rcps.append("To: ").append(to.getString());
        }
        recipients = rcps.toString().trim();
        if (!recipients.endsWith("*")) {
            recipients = recipients + " *";
        }
       /* if (recipients.length() < 6) { //its to short, must be invalid address
            storingBox.report("100: " + Lang.get(Lang.ALRT_SM_NO_RCP), SOURCE_FILE);
            return null;
        }*/
        
        String ID = Functions.genID();
        MessageHeader tmpM = new MessageHeader(storingBox, from.getText(), recipients, subject.getString(), ID, System.currentTimeMillis());
        BodyPart bp = new BodyPart(tmpM, "default_mail_body");
        tmpM.addBodyPart(bp);

        //#ifdef MUJMAIL_FS
        //add attachment file to header if user attached one
        if (getAttachementsAdder().getAttachmentsCount() > 0) {
            // remove all existing file system attachments (in case of editing message)
            tmpM.removeFSAttachments();
            getAttachementsAdder().exportAttachmentsToHeader(tmpM);
            
            tmpM.messageFormat = MessageHeader.FRT_MULTI;
        } else {
            tmpM.messageFormat = MessageHeader.FRT_PLAIN;
        }
        //#else
//#         tmpM.messageFormat = MessageHeader.FRT_PLAIN;
        //#endif

        
        
        // bodyparts are already saved while making deep copy
        try {
            bp.getStorage().addToContent(body.getText() + "\r\n");//body.getString() + "\r\n");

            if (mode == SendMail.EDIT && storingBox == callBox) {
                // the message will be only updated while calling storingBox.mailDB.saveHeader(tmpM);
                // it will be stored to existing database record
                tmpM.setRecordID( storingBox.getMessageHeaderAt( storingBox.getSelectedIndex() ).getRecordID() );
                tmpM.DBStatus = MessageHeader.STORED; //so we can update the old mail in the mailDB.saveHeader()call later
            }


            storingBox.mailDB.saveHeader(tmpM);
        } catch (Exception ex) { //rollback & cleaning
            ex.printStackTrace();
            storingBox.report(ex.getMessage() + " " + subject.getString(), SOURCE_FILE);
            bp.getStorage().deleteContent();
            return null;
        }

        tmpM.updateSize();

        return tmpM;
    }

   

    /**
     * Displays the form for writingn new mail.
     * @param nextScreen
     */
    public void writeMail(Displayable nextScreen) {
        this.nextScreen = nextScreen;
        initFrom();
        MujMail.mujmail.getDisplay().setCurrent(this);
    }

    private void initFrom() {
        from.setText(Settings.primaryEmail);
        //primaryEmail is not set, let's select the first one at least
        if (Settings.primaryEmail.equals(Settings.notSetPE)) {
            for (Enumeration e = mujMail.getMailAccounts().elements(); e.hasMoreElements();) {
                MailAccount account = (MailAccount) e.nextElement();
                if (account.isActive()) {
                    from.setText(account.getEmail());
                    break;
                }
            }
        }
    }

    /**
     * Clears text fields and attachments.
     */
    public void clear() {
        to.setString("");
        subject.setString("");
        body.setText("");//setString("");
        bcc.setString("");
        cc.setString("");
        if (bcc_cc_added) {
            if (DEBUG) System.out.println("SendMail.clear - Deleting from form item on index 2");
           removeComponent(cc);// delete(2);
           removeComponent(bcc);//delete(2);
            addCommand(bc);
            bcc_cc_added = false;
        }
        
        //#ifdef MUJMAIL_FS
        attachementsAdder.removeAllAttachments();
        //#endif
    }

    public void CheckRecordSize(List list) throws RecordStoreException {
        RecordStore rs = RecordStore.openRecordStore("test_this", true);
        try {
            list.append(String.valueOf(rs.getSizeAvailable()), null);
        } finally {
            rs.closeRecordStore();
        }
    }

   
    /**
     * Displays the screen that should follow after this form.
     */
    public void showNextScreen() {
     /*   System.out.println("Next screen is " + nextScreen);
        MujMail.mujmail.getDisplay().setCurrent(nextScreen);*/
       //Aadithya
        if(DEBUG) System.out.println("Next screen is " + nextScreen);

       if (nextScreen == null)
      nextScreen = MujMail.mujmail.getInBox();
        MujMail.mujmail.getDisplay().setCurrent(nextScreen);
  
      //     MujMail.mujmail.getInBox().show();
    }
    //#ifdef SONIMMAIL_CAMERA
   void initSendSnap(){
       to.setString(Settings.defaultEmailSnapshot);
       subject.setString(Settings.defaultSubjectSnapshot);
       //body.setText("This snapshots are captured by SonimMail on"+new java.util.Date());
   }
static int captureCount;
  
  //#endif
 }
